package tt.com.carmanager.controller;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import tt.com.carmanager.service.CarManagerService;
import tt.com.common.enums.Status;
import tt.com.common.model.ClassesTeam;
import tt.com.common.model.DriveTask;
import tt.com.common.model.Team;
import tt.com.common.util.CommonResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;


//车辆调度管理模块
// 前端-后端 /api/car/manager/xxxx
@RestController
@RequestMapping(value = "/car/manager")
public class CarManagerController {

    @Autowired
    private CarManagerService carManagerService;

    @PostMapping(value = "call/taxi")
    public ResponseEntity callTexi(@RequestBody DriveTask task, HttpServletRequest request){
        return carManagerService.appointmentCar(task);
    }


    /**
     * 车辆排班
     * @return
     */
    @GetMapping("/schedule")
    public CommonResult carSchedule(@DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate, @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate){
        System.out.println(startDate);
        List<Team> teams = carManagerService.printTeamByDay(startDate, endDate);
        if (teams == null || teams.size() == 0){
            return CommonResult.buildR(Status.IS_NULL, "该日期范围内无数据");
        }
        return CommonResult.buildR(Status.OK, "查询成功", teams);
    }

    /**
     * 车辆排班表打印日期范围内的数据表格
     * @param startDate 开始时间（包含）
     * @param endDate 结束时间（包含）
     * @return
     */
    @GetMapping("/printScheduleToPDF")
    @ResponseBody
    public CommonResult printCarSchedule(@DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate, @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate, HttpServletResponse response){
        System.out.println(startDate);
        List<ClassesTeam> classesTeams = carManagerService.printPDFByDate(startDate, endDate);
        // 模板路径 关于路径最好放在配置文件中，我这里只想说明问题
        String templatePath = "src\\main\\resources\\printTemplate\\ClassTemplate.pdf";
        // 生成文件路径
        String filename = "testpdf.pdf";


        PdfReader reader;
        OutputStream os = null;
        ByteArrayOutputStream baos = null;
        PdfStamper stamper;

        try {
            os = response.getOutputStream();
            // 读入pdf表单
            reader = new PdfReader(templatePath);
            baos = new ByteArrayOutputStream();
            // 根据表单生成一个新的pdf
            stamper = new PdfStamper(reader, baos);
            // 获取pdf表单
            AcroFields formTexts = stamper.getAcroFields();

            // 设置字体(这里设置为系统字体，你也可以引入其他的字体)，不设置很可能，中文无法显示。
            BaseFont bf = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1",
                    BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            formTexts.addSubstitutionFont(bf);

            // 遍历查询结果
            for (ClassesTeam classesTeam : classesTeams) {
                // 将遍历的数据插入到pdf对应的域中
                formTexts.setField("car_id", classesTeam.getCarId());
                formTexts.setField("start_time", String.valueOf(classesTeam.getStartTime()));
                formTexts.setField("end_time", String.valueOf(classesTeam.getEndTime()));
                formTexts.setField("car_num", classesTeam.getCarNum());
                formTexts.setField("team_id", classesTeam.getTeamId());
                formTexts.setField("create_user_id", classesTeam.getCreateUserId());
            }


            stamper.setFormFlattening(true); // 这个必须设
            stamper.close();

            // 创建一个pdf实例
            Document document = new Document();
            PdfCopy copy = new PdfCopy(document, os);
            document.open();
            PdfImportedPage importedPage = copy.getImportedPage(new PdfReader(baos.toByteArray()), 1);
            copy.addPage(importedPage);
            document.close(); // open和close一套

            // 强制下载
            //response.reset();
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "attachment;fileName="
                    + URLEncoder.encode(filename, "UTF-8"));

        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        } finally { // 最后一定要关闭流
            try {
                baos.close();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return CommonResult.buildR(Status.OK,"成功，请去查看");
    }
//
    }

//    DATE_FORMAT(cla.start_time,'%Y-%m-%d')



